package com.heima.article.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.article.entity.ApArticleContent;
import com.heima.article.service.IApArticleContentService;
import com.heima.common.minio.service.MinIOService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/test")
@Api(tags = "测试生成静态html")
public class TemplateTest {
    @Autowired
    private Configuration configuration;
    @Autowired
    private IApArticleContentService contentService;
    @Autowired
    MinIOService minIOService;
    @GetMapping("/{id}")
    public String template(@PathVariable Long id) throws IOException, TemplateException {

        LambdaQueryWrapper<ApArticleContent> equals = new LambdaQueryWrapper<>();
        equals.eq(ApArticleContent::getArticleId,id);
        ApArticleContent one = contentService.getOne(equals);
        //获取模板
        Template template = configuration.getTemplate("article.ftl");
        //封装数据
        Map<String,Object> map = new HashMap<>();
        map.put("content", JSON.parseArray(one.getContent()));
        //合并模板
        StringWriter out = new StringWriter();
        template.process(map,out);
        //上传静态页面到minion
        InputStream is = new ByteArrayInputStream(out.toString().getBytes());
        String url = minIOService.upload(id + ".html", is, "text/html");
        return url;
    }
}
